/*
 * @Author: C.
 * @Date: 2023-04-03 16:17:54
 */

import fs from 'fs';
import path from 'path';
import ejs from 'ejs';

export const ejsCompile = (templatePath, data = {}, options = {}) => {
  return new Promise((resolve, reject) => {
    ejs.renderFile(templatePath, { data }, options, (err, str) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(str);
    });
  });
};

export const writeFile = (path, content) => {
  // if (fs.existsSync(path)) {
  //   console.error('the file already exists~');
  //   return;
  // }
  return fs.promises.writeFile(path, content);
};

export const mkdirSync = (dirname) => {
  if (fs.existsSync(dirname)) {
    return true;
  } else {
    // 不存在,判断父亲文件夹是否存在？
    if (mkdirSync(path.dirname(dirname))) {
      // 存在父亲文件，就直接新建该文件
      fs.mkdirSync(dirname);
      return true;
    }
  }
};

export const handleEjsToFile = async ({ name, dest, template, filename, title, apiModule }) => {
  // 1.获取模块引擎的路径
  const templatePath = path.resolve(__dirname, template);
  // const cpnPath = dest.replace('router', 'views').replace('src', '@') + `/${name}.vue`;
  // const routePath = dest.replace('/router', '').replace('src', '');
  const result = await ejsCompile(templatePath, {
    name,
    title,
    alias: handleRouteName(name, false),
    api: apiModule + '/' + handleRouteName(name, true),
  });

  // 2.写入文件中
  // 判断文件不存在,那么就创建文件
  mkdirSync(dest);
  const targetPath = path.resolve(dest, filename);
  writeFile(targetPath, result);
};

export function lowerName(name) {
  return name[0].toLowerCase() + name.slice(1);
}
// Sa_Order
export function handleRouteName(name: string, lower = true) {
  const nameList = name.split('_').slice(1);
  return nameList
    .map((item) => {
      return lower ? lowerName(item) : item;
    })
    .join('_');
}
export function handleCURDName(name: string) {
  return lowerName(name.split('_').pop());
}
